package org.darcy.service.privilege.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.darcy.entity.privilege.SysRole;
import org.darcy.entity.privilege.SysUser;
import org.darcy.entity.privilege.SysUserRole;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.service.privilege.SysRoleService;
import org.darcy.service.privilege.SysUserRoleService;
import org.darcy.service.privilege.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

@Service
public class SysUserRoleServiceImpl extends GenericServiceImpl<SysUserRole> implements SysUserRoleService {

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@Override
	public List<Integer> getRoleByUserId(Integer userId) {
		LambdaQueryWrapper<SysUserRole> userGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
		userGroupLambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
		List<SysUserRole> userGroups = this.getList(userGroupLambdaQueryWrapper);
		List<Integer> groupIds = new ArrayList<>();
		userGroups.forEach(userGroup -> groupIds.add(userGroup.getRoleId()));
		return groupIds;
	}

	@Override
	public void addRoleUser(String groupId, List<SysUser> users, SysUser loginUser) {
		if (StringUtils.isNotBlank(groupId)) {
			LambdaQueryWrapper<SysUserRole> userGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
			userGroupLambdaQueryWrapper.eq(SysUserRole::getRoleId, groupId);
			this.deleteBatch(userGroupLambdaQueryWrapper);
		}
		SysRole group = roleService.getById(groupId);
		Date date = new Date();
		if (CollectionUtils.isNotEmpty(users) && StringUtils.isNotBlank(groupId)) {
			users.forEach(user -> {
				SysUserRole userGroup = new SysUserRole();
				userGroup.setUserId(user.getId());
				userGroup.setRoleId(group.getId());
				userGroup.setGroupSn(group.getSn());
				userGroup.setCreateTime(date);
				userGroup.setUpdateTime(date);
				this.insert(userGroup);
			});
		}
	}

	@Override
	public void addUserRole(Integer userId, List<SysRole> groups, SysUser loginUser) {
		if (userId != null) {
			LambdaQueryWrapper<SysUserRole> userGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
			userGroupLambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
			this.deleteBatch(userGroupLambdaQueryWrapper);
		}
		SysUser user = userService.getById(userId);
		Date date = new Date();
		if (CollectionUtils.isNotEmpty(groups) && user != null) {

			groups.forEach(group -> {
				SysUserRole ur = new SysUserRole();
				ur.setUserId(userId);
				ur.setRoleId(group.getId());
				ur.setGroupSn(group.getSn());
				ur.setCreateTime(date);
				ur.setUpdateTime(date);
				this.insert(ur);
			});
		}
	}

}
